<template>
  <view class="admin-user-management-page">
    <view class="page-header">
      <view class="header-left">
        <view class="back-btn" @click="navigateBack">
          <view class="icon icon-arrow-left" style="font-size: 20px;">‹</view>
          <text class="header-title">用户管理</text>
        </view>
      </view>
    </view>
    
    <!-- 搜索区域 -->
    <view class="search-area">
      <view class="search-box">
        <view class="icon icon-search" style="font-size: 16px;">🔍</view>
        <input 
          v-model="searchKeyword" 
          type="text" 
          placeholder="搜索用户名或ID"
          class="search-input"
          @input="onSearch"
        />
      </view>
    </view>
    
    <!-- 用户列表 -->
    <view class="user-list" v-if="!isLoading">
      <view 
        v-for="user in users" 
        :key="user._id"
        class="user-item"
      >
        <view class="user-info">
          <view class="user-avatar">
            <text style="font-size: 28px;">{{ getAvatarIcon(user.username) }}</text>
          </view>
          <view class="user-details">
            <view class="user-name">{{ user.username }}</view>
            <view class="user-meta">
              <text class="meta-item">ID: {{ user._id }}</text>
              <text class="meta-item">注册时间: {{ formatTime(user.create_time) }}</text>
            </view>
            <view class="user-stats">
              <text class="stat-item">收藏: {{ user.collection_count || 0 }}</text>
              <text class="stat-item">下载: {{ user.download_count || 0 }}</text>
              <text class="stat-item">反馈: {{ user.feedback_count || 0 }}</text>
            </view>
          </view>
        </view>
        <view class="user-actions">
          <button 
            class="action-btn view-btn" 
            size="mini" 
            @click="viewUserDetail(user._id)"
          >
            查看详情
          </button>
          <button 
            class="action-btn delete-btn" 
            size="mini" 
            type="warn" 
            @click="confirmDeleteUser(user._id, user.username)"
          >
            删除
          </button>
        </view>
      </view>
      
      <!-- 空状态 -->
      <view v-if="users.length === 0" class="empty-state">
        <view class="icon icon-empty" style="font-size: 48px;">👥</view>
        <text class="empty-text">暂无用户数据</text>
      </view>
    </view>
    
    <!-- 加载中状态 -->
    <view v-else class="loading-state">
      <view class="icon icon-loading" style="font-size: 48px;">⏳</view>
      <text class="loading-text">加载中...</text>
    </view>
    
    <!-- 加载更多 -->
    <view v-if="hasMore && !isLoading" class="load-more">
      <button class="load-more-btn" @click="loadMoreUsers">加载更多</button>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive } from 'vue';
import {onLoad} from"@dcloudio/uni-app"

// 状态管理
const users = ref([]);
const searchKeyword = ref('');
const isLoading = ref(true);
const hasMore = ref(true);
const page = ref(1);
const pageSize = ref(20);

// 生命周期
onLoad(() => {
  // 移除管理员权限校验
  loadUsers();
});

// 管理员权限校验已移除

// 加载用户列表
const loadUsers = async (isLoadMore = false) => {
  if (isLoading.value) return;
  
  try {
    isLoading.value = true;
    
    const result = await uniCloud.callFunction({
      name: 'admingetUsers',
      data: {
        page: isLoadMore ? page.value : 1,
        pageSize: pageSize.value,
        keyword: searchKeyword.value.trim()
      }
    });
    
    if (result && result.result && result.result.code === 0) {
      const newUsers = result.result.data || [];
      
      if (isLoadMore) {
        users.value = [...users.value, ...newUsers];
      } else {
        users.value = newUsers;
        page.value = 1;
      }
      
      hasMore.value = newUsers.length === pageSize.value;
      
      if (isLoadMore && hasMore.value) {
        page.value++;
      }
    } else {
      uni.showToast({ 
        title: result.result?.message || '加载用户失败', 
        icon: 'none' 
      });
      // 使用模拟数据
      if (!isLoadMore) {
        mockUsers();
      }
    }
  } catch (error) {
    console.error('加载用户失败:', error);
    // 使用模拟数据
    if (!isLoadMore) {
      mockUsers();
    }
  } finally {
    isLoading.value = false;
  }
};

// 模拟用户数据
const mockUsers = () => {
  users.value = [
    {
      _id: 'u1',
      username: 'testuser1',
      create_time: Date.now() - 86400000 * 7,
      collection_count: 12,
      download_count: 25,
      feedback_count: 2
    },
    {
      _id: 'u2',
      username: 'wallpaper_lover',
      create_time: Date.now() - 86400000 * 14,
      collection_count: 45,
      download_count: 89,
      feedback_count: 1
    },
    {
      _id: 'u3',
      username: 'designer_pro',
      create_time: Date.now() - 86400000 * 30,
      collection_count: 78,
      download_count: 132,
      feedback_count: 5
    }
  ];
  hasMore.value = false;
};

// 获取头像图标
const getAvatarIcon = (username) => {
  const icons = ['👤', '👨‍💻', '👩‍💻', '👨‍🎨', '👩‍🎨', '🎨', '📸', '🖼️'];
  let sum = 0;
  for (let i = 0; i < username.length; i++) {
    sum += username.charCodeAt(i);
  }
  return icons[sum % icons.length];
};

// 格式化时间
const formatTime = (timestamp) => {
  if (!timestamp) return '';
  const date = new Date(timestamp);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
};

// 搜索用户
const onSearch = () => {
  clearTimeout(window.searchTimer);
  window.searchTimer = setTimeout(() => {
    loadUsers();
  }, 300);
};

// 加载更多用户
const loadMoreUsers = () => {
  if (hasMore.value && !isLoading.value) {
    loadUsers(true);
  }
};

// 查看用户详情
const viewUserDetail = (userId) => {
  // 这里可以跳转到用户详情页面
  uni.showToast({
    title: '查看用户详情功能开发中',
    icon: 'none'
  });
};

// 确认删除用户
const confirmDeleteUser = (userId, username) => {
  uni.showModal({
    title: '确认删除',
    content: `确定要删除用户「${username}」吗？此操作不可恢复。`,
    success: async (res) => {
      if (res.confirm) {
        await deleteUser(userId);
      }
    }
  });
};

// 删除用户
const deleteUser = async (userId) => {
  try {
    uni.showLoading({ title: '删除中' });
    
    const result = await uniCloud.callFunction({
      name: 'admindeleteUser',
      data: { id: userId }
    });
    
    uni.hideLoading();
    
    if (result && result.result && result.result.code === 0) {
      uni.showToast({
        title: '删除成功',
        icon: 'success',
        duration: 1500,
        complete: () => {
          // 重新加载用户列表
          loadUsers();
        }
      });
    } else {
      uni.showToast({ 
        title: result.result?.message || '删除失败', 
        icon: 'none' 
      });
    }
  } catch (error) {
    console.error('删除用户失败:', error);
    uni.hideLoading();
    uni.showToast({ 
      title: '删除失败，请稍后重试', 
      icon: 'none' 
    });
  }
};

// 导航返回
const navigateBack = () => {
  uni.navigateBack();
};
</script>

<style scoped lang="less">
.icon {
  display: inline-flex;
  align-items: center;
  justify-content: center;
}
.admin-user-management-page {
  background-color: #f5f5f5;
  min-height: 100vh;
  
  .page-header {
    display: flex;
    padding: 16px;
    background-color: #fff;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
    
    .header-left {
      .back-btn {
        display: flex;
        align-items: center;
        
        .header-title {
          font-size: 18px;
          font-weight: 600;
          color: #333;
          margin-left: 4px;
        }
      }
    }
  }
  
  .search-area {
    padding: 16px;
    background-color: #fff;
    
    .search-box {
      display: flex;
      align-items: center;
      background-color: #f5f5f5;
      border-radius: 8px;
      padding: 0 12px;
      height: 40px;
      
      .search-input {
        flex: 1;
        margin-left: 8px;
        font-size: 14px;
        height: 100%;
      }
    }
  }
  
  .user-list {
    padding: 16px;
    
    .user-item {
      background-color: #fff;
      border-radius: 12px;
      padding: 16px;
      margin-bottom: 16px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
      
      .user-info {
        display: flex;
        margin-bottom: 12px;
        
        .user-avatar {
          width: 56px;
          height: 56px;
          border-radius: 50%;
          background-color: #f0f8ff;
          display: flex;
          align-items: center;
          justify-content: center;
          margin-right: 12px;
        }
        
        .user-details {
          flex: 1;
          
          .user-name {
            font-size: 16px;
            font-weight: 600;
            color: #333;
            margin-bottom: 4px;
          }
          
          .user-meta {
            font-size: 12px;
            color: #666;
            margin-bottom: 4px;
            
            .meta-item {
              margin-right: 12px;
            }
          }
          
          .user-stats {
            font-size: 12px;
            color: #999;
            
            .stat-item {
              margin-right: 12px;
            }
          }
        }
      }
      
      .user-actions {
        display: flex;
        justify-content: flex-end;
        gap: 8px;
      }
    }
    
    .empty-state {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      padding: 64px 0;
      
      .empty-text {
        font-size: 14px;
        color: #666;
        margin-top: 16px;
      }
    }
  }
  
  .loading-state {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 64px 0;
    
    .loading-text {
      font-size: 14px;
      color: #666;
      margin-top: 16px;
    }
  }
  
  .load-more {
    padding: 16px;
    text-align: center;
    
    .load-more-btn {
      font-size: 14px;
      color: #007aff;
      background-color: transparent;
    }
  }
}
</style>